/*
Copyright (c) [2019年5月1日] [吴超]
[MBT_studio] is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
#include "stdafx.h"

#include "面/面.h"
#include "外部库/XML/rapidxml.hpp"

#define NANOSVG_IMPLEMENTATION
#include "nanosvg/nanosvg.h"

#include <clipper2/clipper.h>


#include <sstream>

//#pragma comment(lib, "Clipper2.lib")
//#pragma comment(lib, "Clipper2Z.lib")




enum E_SVG元素 {
	E_空,
	E_三次曲线,
	E_二次曲线,
	E_直线,
	E_H直线,
	E_V直线,
	E_圆弧,
};

//Clipper2Lib::TriangulatePolygon();

// 嵌套关系结果结构体
struct NestingResult  {
	std::map<size_t, E_PathType2D>	path_type;       // 路径类型（用索引标识路径）
	std::map<size_t, size_t>		parent_index;    // 父路径索引（-1表示无父路径）
	std::vector<size_t>				all_outer_indices; // 所有外圈的索引列表
};

class C_路径嵌套关系 {
	
	const double scale_;        // 缩放因子（将32位浮点转为64位整数）
	const double inv_scale_;    // 逆缩放因子（用于调试输出）

	/**
	* 将32位vec2路径转换为Clipper2可用的64位整数路径
	* @param path 32位浮点顶点组成的路径
	* @return 转换后的64位整数路径
	*/
	Clipper2Lib::Path64 ToPath64(const std::vector<vec2>& path) const {
		Clipper2Lib::Path64 result;
		result.reserve(path.size());

		for (const auto& pt : path) {
			// 四舍五入转换，保留精度
			int64_t x = static_cast<int64_t>(std::round(pt.x * scale_));
			int64_t y = static_cast<int64_t>(std::round(pt.y * scale_));
			result.emplace_back(x, y);
		}

		return result;
	}

	/**
	* 批量转换32位路径集合为64位整数路径集合
	* @param paths 32位浮点路径集合
	* @return 转换后的64位整数路径集合
	*/
	std::vector<Clipper2Lib::Path64> ToPaths64(const std::vector<std::vector<vec2>>& paths) const {
		std::vector<Clipper2Lib::Path64> result;
		result.reserve(paths.size());

		for (const auto& path : paths) {
			result.push_back(ToPath64(path));
		}

		return result;
	}

	/**
	* 判断路径A是否被路径B完全包含
	* @param a_idx 路径A的索引
	* @param b_idx 路径B的索引
	* @param paths64 转换后的64位路径集合
	* @return true表示A被B包含，false otherwise
	*/
	bool IsContained(size_t a_idx, 
					 size_t b_idx, 
					 const std::vector<Clipper2Lib::Path64>& paths64) const 
	{
		const auto& path_a = paths64[a_idx];
		const auto& path_b = paths64[b_idx];

		// 过滤无效多边形（顶点数不足3）
		if (path_a.size() < 3 || path_b.size() < 3) {
			return false;
		}

		// 检查A的所有顶点是否在B内部
		for (const auto& pt : path_a) 
		{
			auto pip_result = Clipper2Lib::PointInPolygon(pt, path_b);
			if (pip_result == Clipper2Lib::PointInPolygonResult::IsOutside) {
				return false;
			}
		}

		// 检查A的中心点是否在B内部（处理边界顶点特殊情况）
		Clipper2Lib::Rect64 bounds = Clipper2Lib::GetBounds(path_a);
		Clipper2Lib::Point64 center = bounds.MidPoint();

		return Clipper2Lib::PointInPolygon(center, path_b) == Clipper2Lib::PointInPolygonResult::IsInside;
	}

	/**
	* 判断路径是否为顺时针方向
	* @param path 64位整数路径
	* @return true表示顺时针，false表示逆时针
	*/
	bool IsClockwise(const Clipper2Lib::Path64& path) const {
		int64_t area_sum = 0;
		size_t vertex_count = path.size();

		for (size_t i = 0; i < vertex_count; ++i) {
			size_t j = (i + 1) % vertex_count;
			area_sum += static_cast<int64_t>(path[i].x) * path[j].y 
				- static_cast<int64_t>(path[j].x) * path[i].y;
		}

		// 面积和为负 → 顺时针
		return area_sum < 0;
	}

	/**
	* 查找路径a的直接父路径（最内层包含它的路径）
	* @param a_idx 路径a的索引
	* @param paths64 转换后的64位路径集合
	* @return 父路径索引，-1表示无父路径
	*/
	int64_t FindDirectParent(size_t a_idx,  const std::vector<Clipper2Lib::Path64>& paths64) const {
		int64_t parent_idx = -1;

		for (size_t b_idx = 0; b_idx < paths64.size(); ++b_idx) {
			if (a_idx == b_idx) {
				continue; // 跳过自身
			}

			if (IsContained(a_idx, b_idx, paths64)) {
				// 优先选择"最小"的父路径（直接包含当前路径的路径）
				if (parent_idx == -1 || IsContained(parent_idx, b_idx, paths64)) {
					parent_idx = b_idx;
				}
			}
		}

		return parent_idx;
	}

public:
	/**
	* 构造函数
	* @param scale 缩放因子（建议1e3 ~ 1e6，根据精度需求调整）
	*/
	C_路径嵌套关系(double scale) 
		: scale_(scale), 
		inv_scale_(1.0 / scale) 
	{
		if (scale <= 0) {
			throw std::invalid_argument("缩放因子必须为正数");
		}
	}

	/**
	* 核心分类函数：区分外圈和孔，建立嵌套关系
	* @param all_paths 32位vec2路径集合
	* @return 嵌套关系结果
	*/
	NestingResult ClassifyPaths(const std::vector<std::vector<vec2>>& all_paths) const {
		NestingResult result;
		std::vector<size_t> valid_indices;

		// 1. 将所有路径转换为64位整数格式（Clipper2需要）
		auto paths64 = ToPaths64(all_paths);

		// 2. 过滤无效路径（顶点数不足3的多边形）
		for (size_t i = 0; i < all_paths.size(); ++i) {
			if (all_paths[i].size() >= 3) 
			{
				valid_indices.push_back(i);
			}
		}

		// 3. 确定所有有效路径的直接父路径
		std::map<size_t, int64_t> parent_map;
		for (size_t a_idx : valid_indices) {
			parent_map[a_idx] = FindDirectParent(a_idx, paths64);
		}

		// 4. 识别最顶层外圈（无父路径的路径）
		for (size_t idx : valid_indices) {
			if (parent_map[idx] == -1) {
				result.path_type[idx] = E_PathType2D::OuterRing;
				result.all_outer_indices.push_back(idx);
				result.parent_index[idx] = -1;
			}
		}

		// 5. 识别嵌套外圈和孔（结合方向判断）
		for (size_t idx : valid_indices) {
			// 跳过已识别的最顶层外圈
			if (result.path_type.count(idx)) {
				continue;
			}

			int64_t parent_idx = parent_map[idx];
			if (parent_idx == -1) {
				continue; // 无效父路径（理论上不会出现）
			}

			// 判断子路径与父路径的方向
			bool child_cw = IsClockwise(paths64[idx]);
			bool parent_cw = IsClockwise(paths64[parent_idx]);

			// 方向相反 → 孔；方向相同 → 嵌套外圈
			if (child_cw != parent_cw) {
				result.path_type[idx] = E_PathType2D::Hole;
				result.parent_index[idx] = parent_idx;
			} 
			else {
				result.path_type[idx] = E_PathType2D::OuterRing;
				result.all_outer_indices.push_back(idx);
				result.parent_index[idx] = parent_idx;
			}
		}

		return result;
	}

};







// 计算向量的角度
float vectorAngle(float x, float y) {
	return std::atan2(y, x);
}

// 生成圆弧上的坐标点
static std::vector<vec2> arcToCubicBezier(vec2 start, vec2 end, float rx, float ry, float rotation, bool largeArcFlag, bool sweepFlag) {
	// 转换旋转角度到弧度
	float32 rotationRadians = M_角度转弧度(rotation);

	// 计算中点
	vec2 mid = (start + end) * 0.5;

	// 旋转坐标系，使椭圆的轴与坐标轴对齐
	Vec2 rotatedStart(
		std::cos(rotationRadians) * (start.x - mid.x) - std::sin(rotationRadians) * (start.y - mid.y),
		std::sin(rotationRadians) * (start.x - mid.x) + std::cos(rotationRadians) * (start.y - mid.y)
	);
	Vec2 rotatedEnd(
		std::cos(rotationRadians) * (end.x - mid.x) - std::sin(rotationRadians) * (end.y - mid.y),
		std::sin(rotationRadians) * (end.x - mid.x) + std::cos(rotationRadians) * (end.y - mid.y)
	);

	// 确保半径非负
	rx = std::abs(rx);
	ry = std::abs(ry);

	// 计算半径缩放因子
	float scaleFactor = (rotatedStart.x * rotatedStart.x) / (rx * rx) + (rotatedStart.y * rotatedStart.y) / (ry * ry);
	if (scaleFactor > 1.0f) {
		float scale = std::sqrt(scaleFactor);
		rx *= scale;
		ry *= scale;
	}

	// 计算圆心
	float sign = (largeArcFlag == sweepFlag) ? -1.0f : 1.0f;
	float factor = std::sqrt(std::max(0.0f, ((rx * rx) * (ry * ry) - (rx * rx) * (rotatedEnd.y * rotatedEnd.y) - (ry * ry) * (rotatedEnd.x * rotatedEnd.x)) / ((rx * rx) * (rotatedEnd.y * rotatedEnd.y) + (ry * ry) * (rotatedEnd.x * rotatedEnd.x))));
	Vec2 rotatedCenter(
		sign * factor * rx * rotatedEnd.y / ry,
		-sign * factor * ry * rotatedEnd.x / rx
	);
	Vec2 center(
		std::cos(rotationRadians) * rotatedCenter.x - std::sin(rotationRadians) * rotatedCenter.y + mid.x,
		std::sin(rotationRadians) * rotatedCenter.x + std::cos(rotationRadians) * rotatedCenter.y + mid.y
	);

	// 计算起始和结束角度
	float startAngle = vectorAngle(rotatedStart.x - rotatedCenter.x, rotatedStart.y - rotatedCenter.y);
	float endAngle = vectorAngle(rotatedEnd.x - rotatedCenter.x, rotatedEnd.y - rotatedCenter.y);
	float angleDifference = endAngle - startAngle;
	if (sweepFlag && angleDifference < 0.0f) {
		angleDifference += 2.0f * M_PI;
	} else if (!sweepFlag && angleDifference > 0.0f) {
		angleDifference -= 2.0f * M_PI;
	}

	// 分割圆弧为一个三次贝塞尔曲线（简化处理）
	float alpha = std::tan(angleDifference / 4.0f) * 4.0f / 3.0f;
	vec2 controlPoint1{
		start.x + alpha * (start.y - center.y),
		start.y - alpha * (start.x - center.x)
	};
	vec2 controlPoint2{
		end.x - alpha * (end.y - center.y),
		end.y + alpha * (end.x - center.x)
	};

	return {start, controlPoint1, controlPoint2, end};
}

// 计算圆心
vec2 f_calculateCenter(const vec2& start, const vec2& end, vec2 半径, bool 大弧, bool sweepFlag) {
	vec2 mid = (start + end) * 0.5;
	float32 dx = (start.x - end.x) / 2;
	float32 dy = (start.y - end.y) / 2;
	float32 d2 = dx * dx + dy * dy;

	double sfactor = 1;
	if (大弧 == sweepFlag) {
		sfactor = -1;
	}
	float32 numerator = 半径.x * 半径.x * 半径.y * 半径.y - 半径.x * 半径.x * dy * dy - 半径.y * 半径.y * dx * dx;
	if (numerator < 0) {
		float32 s = std::sqrt(d2 / (半径.x * 半径.x / 半径.y / 半径.y + dy * dy / dx / dx));
		半径.x *= s;
		半径.y *= s;
	}
	float32 q = std::sqrt(std::abs(numerator) / (半径.x * 半径.x * dy * dy + 半径.y * 半径.y * dx * dx));
	float32 cx = mid.x + sfactor * q * 半径.x * dy / 半径.y;
	float32 cy = mid.y - sfactor * q * 半径.y * dx / 半径.x;

	return { cx, cy };
}

static std::vector<vec2> f_构建圆弧曲线(vec2 start, vec2 end, vec2 半径, int32 方向) {
	vec2 中心 = f_calculateCenter(start, end, 半径, 0, 方向);
	
	float32 osa = f_graph_vectorAngle(normalize(start - 中心));
	float32 osb = f_graph_vectorAngle(normalize(end - 中心));

	float32 角度 = abs(M_弧度转角度(osb - osa));
	//if (osb < 0) {
	//	角度 = M_弧度转角度(osa + abs(osb));
	//}

	std::vector<vec2> point = f_graph_计算圆坐标(中心, 半径, 6, M_弧度转角度(osa), 角度, 方向 == 1 ? 1 : -1);

	return point;
}

Inline bool f_是否为元素标记(const std::string& s) {
	if (s == "Z" || s == "z" || s == "L" || s == "l" || s == "H" || s == "h" || s == "V" || s == "v" || s == "Q" || s == "q" || s == "C" || s == "c" || s == "a" || s == "A") return true;
	return false;
}

Inline S_RGBA8UI f_解析SVG颜色(const std::string& val) {
	uint32 颜色 = std::stoul(val, nullptr, 16);
	auto rgb = f_UpPackDataRGB(颜色);

	S_RGBA8UI color{};
	color.r = rgb.b;
	color.g = rgb.g;
	color.b = rgb.r;

	return color;
}
static mat3X2 f_读取变换矩阵(std::istringstream& iss) {
	mat3X2 mat = f_mat3x2_identity();
	std::string val;
	iss>>val;
	val = val.substr(val.find('('), val.find(')'));
	val.pop_back();

	auto spos = 1;
	
	std::vector<float32> m;
	while (spos < val.size()) {
		auto epos = val.find(',', spos);

		m.emplace_back(std::stof(val.substr(spos, epos)));
		if(epos >= std::string::npos) break;

		spos = epos+1;
	}

	if (m.size() == 2) {
		mat.row2 = {m[0], m[1]};
	}
	else if (m.size() == 6) {
		for(uint32 i=0; i<6; ++i) ((float32*)&mat)[i] = m[i];
	}
	

	return mat;
}

static void f_读取梯度渐变(rapidxml::xml_node<>* node) {
	
}


static S_2D图元属性 f_图形属性读取(std::istringstream& iss) {
	std::string token;
	S_2D图元属性 style{};
	
	while (iss.eof() == false) {
		
		auto 颜色填充解析 = [&]() -> int32 {
			if (token == "none") {
				return 0;
			}
			else {
				if (token.front() == '#') {
					auto 颜色 = f_解析SVG颜色(token.substr(1, token.size()));
					style.填充颜色.r = 颜色.r;
					style.填充颜色.g = 颜色.g;
					style.填充颜色.b = 颜色.b;
					return 1;
				}
				else {
					auto url = token.substr(0, 3);
					if (url == "url") {
						style.效果引用 = token.substr(5, token.size());
						style.效果引用.pop_back();
						return 2;
					}
				}
			}
			return 0;
		};


		std::getline(iss, token, ':');
		if (token == "fill") {
			std::getline(iss, token, ';');
			style.填充 |= 颜色填充解析();
		}
		else if (token == "fill-opacity") {
			std::getline(iss, token, ';');
			style.填充颜色.a = std::stof(token) * 255;
		}
		else if (token == "stroke") {
			std::getline(iss, token, ';');
			style.描边 |= 颜色填充解析()<<2;
		}
		else if (token == "stroke-opacity") {
			std::getline(iss, token, ';');
			style.填充颜色.a = std::stof(token) * 255;
		}
		else if (token == "stroke-width") {
			std::getline(iss, token, ';');
			style.线宽 = std::stof(token);
		}
		else {
			std::getline(iss, token, ';');
		}
	}

	return style;
}

void parseNode(rapidxml::xml_node<>* node, S_PolygonDataGroup& polygons, const mat3X2& parseMat) {
	float32 s = 1/8.0f;
	std::string type = node->name();
	mat3X2 当前矩阵 = f_mat3x2_identity();


	auto 属性 = [](std::istringstream& iis, rapidxml::xml_node<>* 节点, const std::string name) -> bool {
		rapidxml::xml_attribute<>* styleAttr = 节点->first_attribute(name.c_str());
		if (styleAttr) {
			auto attr = styleAttr->value();
			iis = std::istringstream(std::string(attr));
			return true;
		}
		return false;
	};

	if (type == "path") {
		std::vector<uint32> 边索引;
		PolygonData polygon;

		std::istringstream iss;
		if (属性(iss, node, "style")) {
			polygon.style = f_图形属性读取(iss);
		}
		else {
			polygon.style = {};
		}

		rapidxml::xml_attribute<>* dAttr = node->first_attribute("d");
		if (dAttr) {
			auto dAttribute = dAttr->value();
			iss.str(std::string(dAttribute));
			std::string token;

			auto pos = iss.tellg();
			
			vec2 beginPoint{};
			//vec2 currentPoint{};
			bool 相对坐标 = false;

			auto f = [&](const vec2& v)->vec2{
				//return vec2{v.x, polygon.bound.y - v.y} / polygon.bound;
				//if (v.x > polygons.bound.x || v.y > polygons.bound.y) {
				//	std::cout<<"\n";
				//}
				//if (v.x > 80 || v.y > 80) {
				//	std::cout<<"\n";
				//}
				if(v.x > polygons.maxBound.x) polygons.maxBound.x = v.x;
				if(v.y > polygons.maxBound.y) polygons.maxBound.y = v.y;

				if(v.x < polygons.minBound.x) polygons.minBound.x = v.x;
				if(v.y < polygons.minBound.y) polygons.minBound.y = v.y;

				//polygons.maxBound = max(polygons.maxBound, v);
				//polygons.minBound = min(polygons.minBound, v);
				//return vec2{v.x, v.y};
				//return parseMat * vec2{v.x, v.y};
				return 当前矩阵 * vec2{v.x, v.y};
			};


			std::vector<vec2> 连续顶点;
			E_SVG元素 当前读取元素类型;

			iss.clear();
			while (iss.eof() == false) {
				auto posA = iss.tellg();

				std::getline(iss, token, ' '); 
				
				if (token == "M" || token == "m") {
					当前读取元素类型 = E_SVG元素::E_空;
					if (token == "m") {
						相对坐标 = true;
					}else {
						相对坐标 = false;
					}
					连续顶点.clear();
				}
				else if (token == "L" || token == "l" || token == "H" || token == "h" || token == "V" || token == "v") {
					
					float32 x = 0, y = 0;
					if (token == "L" || token == "l") {
						当前读取元素类型 = E_SVG元素::E_直线;

						if (token == "l") {
							相对坐标 = true;
						}else {
							相对坐标 = false;
						}
					} else if (token == "H" || token == "h") {
						当前读取元素类型 = E_SVG元素::E_H直线;
						//iss >> x;
						if (token == "h") {
							相对坐标 = true;
						} else {
							相对坐标 = false;
						}
					} else if (token == "V" || token == "v") {
						当前读取元素类型 = E_SVG元素::E_V直线;
						//iss >> y;
						if (token == "v") {
							相对坐标 = true;
						} else {
							相对坐标 = false;
						}
					}
				}
				else if (token == "Q" || token == "q") {
					当前读取元素类型 = E_SVG元素::E_二次曲线;
					if (token == "q") {
						相对坐标 = true;
					}else {
						相对坐标 = false;
					}
				}
				else if (token == "C" || token == "c") {
					当前读取元素类型 = E_SVG元素::E_三次曲线;

					if (token == "c") {
						相对坐标 = true;
					}else {
						相对坐标 = false;
					}
				}
				else if (token == "a" || token == "A") {
					当前读取元素类型 = E_SVG元素::E_圆弧;

					if (token == "a") {
						相对坐标 = true;
					}else {
						相对坐标 = false;
					}

					while (iss.eof() == false) {
						auto 坐标解析 = [&]() -> vec2 {
							vec2 v;
							std::getline(iss, token, ' '); 

							size_t commaPos = token.find(',');
							if (commaPos != std::string::npos) {
								v.x = std::stof(token.substr(0, commaPos));
								v.y = std::stof(token.substr(commaPos+1, token.size()));
							}
							else {
								v.x = std::stof(token);
								std::getline(iss, token, ' '); 
								v.y = std::stof(token);
							}
							return v;
						};

						
						vec2 圆弧比例 = 坐标解析();
						
						std::getline(iss, token, ' '); 
						float32 旋转角度 = std::stof(token);

						std::getline(iss, token, ' '); 
						int32 大弧 = std::stoi(token);

						std::getline(iss, token, ' '); 
						int32 方向 = std::stoi(token);


						vec2 起点坐标 = 连续顶点.front();
						vec2 终点坐标 = 坐标解析();

						if(相对坐标) {
							终点坐标 += 起点坐标;
						}
						auto 圆弧顶点 = f_构建圆弧曲线(起点坐标, 终点坐标, 圆弧比例, 方向);

						for (auto& e : 圆弧顶点) {
							边索引.emplace_back(polygon.point.size());
							polygon.point.emplace_back(f(e));
						}
						连续顶点 = {终点坐标};


						std::streampos initialPos = iss.tellg();
						iss >> token;
						iss.seekg(initialPos);
						if (f_是否为元素标记(token)) {
							break;
						}
					}

					
				}
				else if (token == "Z" || token == "z") {
					if (边索引.size()) {
						if (连续顶点.size()) {
							边索引.emplace_back(polygon.point.size());
							polygon.point.emplace_back(f(连续顶点.back()));
						}
						//边索引.emplace_back(边索引.front());
						polygon.edges.emplace_back(std::move(边索引));

					}
					边索引.clear();
				}
				else if(token != "") {
					std::stringstream sf(token);
					vec2 c{};
					
					uint32 当前点数量 = 连续顶点.size();
					std::string v;
					switch (当前读取元素类型) {
						case E_H直线: {
							sf>>v;
							c.x = std::stof(v);
							if(当前点数量 && !相对坐标) {
								c.y = 连续顶点.front().y;
							}
							break;
						}
						case E_V直线: {
							sf>>v;
							c.y = std::stof(v);
							if(当前点数量 && !相对坐标) {
								c.x = 连续顶点.front().x;
							}
							break;
						}
						
						default: {
							size_t commaPos = token.find(',');
							if (commaPos != std::string::npos) {
								std::getline(sf, token, ',');
								c.x = std::stof(token);
								std::getline(sf, token, ','); 
								c.y = std::stof(token);
							}
							else {
								c.x = std::stof(token);
								iss >> token;
								c.y = std::stof(token);
							}
							
							break;
						}
					}
					if (相对坐标) {
						if(当前点数量) {
							c += 连续顶点.front();
						}
						连续顶点.emplace_back(c);
					}
					else {
						连续顶点.emplace_back(c);
						beginPoint = c;
					}
					


					
					uint32 num = 连续顶点.size();
					switch (当前读取元素类型) {
						
						case E_三次曲线: {
							if (num >= 4) {
								for (uint32 i = 0; i < 8; ++i) {
									vec2 p = f_cubicCurve_sample(连续顶点[0], 连续顶点[1], 连续顶点[2], 连续顶点[3], s * i);

									边索引.emplace_back(polygon.point.size());
									polygon.point.emplace_back(f(p));
								}
								if (相对坐标) {
									
								}
								连续顶点 = {连续顶点.back()};
							}
							break;
						}
						case E_二次曲线: {
							if (num >= 3) {
								//f_quadraticCurve_sample()
								连续顶点 = {连续顶点.back()};
							}
							break;
						}


						case E_SVG元素::E_空:
						case E_H直线:
						case E_V直线:
						case E_直线: {
							if (连续顶点.size() > 1) {
								uint32 num = 连续顶点.size() - 1;
								for (uint32 i=0; i<num; ++i) {
									边索引.emplace_back(polygon.point.size());
									polygon.point.emplace_back(f(连续顶点[i]));
								}
								连续顶点 = {连续顶点.back()};
							}
							break;
						}
						
						case E_SVG元素::E_圆弧: {
							if (num >= 6) {
								
							}
							break;
						}
						default:
							break;
					}
				}
				token.clear();
			}

			polygons.graph.emplace_back(std::move(polygon));
		}

		
	}
	

	std::istringstream iss;
	
	if (type == "linearGradient") {
		if (属性(iss, node, "id")) {
			std::string ID;
			iss>>ID;

			if (属性(iss, node, "xlink:href")) {
				S_2D渐变控制 线性渐变控制;
				iss>>线性渐变控制.colorKey; 
				
				std::string val;
				if(属性(iss, node, "x1")) iss >> val; 线性渐变控制.xy1.x = std::stof(val);
				if(属性(iss, node, "y1")) iss >> val; 线性渐变控制.xy1.y = std::stof(val);
				if(属性(iss, node, "x2")) iss >> val; 线性渐变控制.xy2.x = std::stof(val);
				if(属性(iss, node, "y2")) iss >> val; 线性渐变控制.xy2.y = std::stof(val);

				if(属性(iss, node, "gradientTransform")) 当前矩阵 = parseMat * f_读取变换矩阵(iss);

				线性渐变控制.xy1 *= 当前矩阵;
				线性渐变控制.xy2 *= 当前矩阵;
				polygons.效果控制[ID] = 线性渐变控制;
			}
			else {
				for (rapidxml::xml_node<>* subNode = node->first_node(); subNode; subNode = subNode->next_sibling()) {
					std::string subType = subNode->name();

					S_2D_EffectLinearGradient 渐变点;

					if (属性(iss, subNode, "style")){
						std::string val;
						std::getline(iss, val, ':');
						std::getline(iss, val, ';');

						S_RGBA8UI color{};
						if (val.front() == '#') {
							val.erase(0,1);
							color = f_解析SVG颜色(val);
						}
						
						std::getline(iss, val, ':');
						std::getline(iss, val, ';');
						color.a = std::stof(val);
						
						渐变点.color = f_PackData4X8(color);
					}
					if (属性(iss, subNode, "offset")){
						std::string offset;
						iss >> offset;
						渐变点.offset = std::stof(offset);
					}

					polygons.渐变颜色[ID].push_back(渐变点);
				}
			}
		}
		return;
	}

	if (type == "radialGradient") {
		if (属性(iss, node, "id")) {
			std::string ID;
			iss>>ID;

			S_2D渐变控制 径向渐变控制;
			if (属性(iss, node, "gradientTransform")) {
				当前矩阵 = parseMat * f_读取变换矩阵(iss);
			}

			std::string val;
			if (属性(iss, node, "xlink:href")) {
				iss>>val;
				if (val.front() == '#') {
					val.erase(0, 1);
					径向渐变控制.colorKey = val;
				}
			}
			if (属性(iss, node, "cx")) {
				iss>>val; 径向渐变控制.xy1.x = std::stof(val);
			}
			if (属性(iss, node, "cy")) {
				iss>>val; 径向渐变控制.xy1.x = std::stof(val);
			}
			if (属性(iss, node, "fx")) {
				iss>>val; 径向渐变控制.xy2.x = std::stof(val);
			}
			if (属性(iss, node, "fy")) {
				iss>>val; 径向渐变控制.xy2.x = std::stof(val);
			}
			if (属性(iss, node, "r")) {
				iss>>val; 径向渐变控制.r = std::stof(val);
			}
			polygons.效果控制[ID] = 径向渐变控制;
		}
	}
	
	if (type == "g") {
		if (属性(iss, node, "transform")) {
			当前矩阵 = parseMat * f_读取变换矩阵(iss);
		}
	}

	// 递归处理子节点
	for (rapidxml::xml_node<>* subNode = node->first_node(); subNode; subNode = subNode->next_sibling()) {
		parseNode(subNode, polygons, 当前矩阵);
	}
}

static PolygonData f_nsvg_Gpath(NSVGshape* shape) {
	PolygonData polygon;

	NSVGpath* path;	
	int32 pathIndex = 0; 
	const float32 s = 1/8.0f;


	std::vector<std::vector<vec2>> 未插值路径;
	//CGAL::Polygon;
	
	
	// 遍历当前图形内的所有路径
	for (path = shape->paths; path != nullptr; path = path->next, ++pathIndex) {
		std::vector<vec2> 路径顶点;
		std::vector<uint32> 边索引;

		bool 添加末尾顶点 = false;

		vec2* svgVert = (vec2*)path->pts;
		int32 line_i = 0;

		for (; line_i < path->npts - 1; line_i += 3) {
			vec2* ov = &svgVert[line_i];

			vec2 a = ov[0] - ov[1];
			vec2 b = ov[3] - ov[2];

			if (abs(dot(normalize(a), normalize(b))) < 0.999999 ) {
				for (uint32 i = 0; i < 8; ++i) {
					vec2 p = f_cubicCurve_sample(ov[0], ov[1], ov[2], ov[3], s * i);

					边索引.emplace_back(polygon.point.size());
					polygon.point.emplace_back(p);
				}
				添加末尾顶点 = false;
			}
			else {
				边索引.emplace_back(polygon.point.size());
				polygon.point.emplace_back(ov[0]);

				//边索引.emplace_back(polygon.point.size());
				//polygon.point.emplace_back(ov[3]);
				添加末尾顶点 = true;
			}

			
			路径顶点.emplace_back(ov[0]);
		}
		//if (path->closed) {
		//	vec2* ov_s = &svgVert[0];
		//	vec2* ov = &svgVert[path->npts - 2];
		//
		//	//边索引.emplace_back(polygon.point.size());
		//	//polygon.point.emplace_back(ov[0]);
		//
		//	//边索引.emplace_back(polygon.point.size());
		//	//polygon.point.emplace_back(svgVert[path->npts-1]);
		//	
		//	//路径顶点.emplace_back(ov_s[0]);
		//}
		//else {
		//	std::cout << "\n";
		//}

		polygon.edges.push_back(边索引);
		未插值路径.push_back(std::move(路径顶点));
	}

	if (shape->fillRule) {
		std::cout<<polygon.style.填充;
	}

	//C_路径嵌套关系 嵌套判断(1);
	//auto 嵌套关系 = 嵌套判断.ClassifyPaths(未插值路径);
	//uint32 num = 未插值路径.size();
	//for (uint32 i = 0; i < num; ++i) {
	//	polygon.path_type.emplace_back(嵌套关系.path_type[i]);
	//}

	
	return polygon;
}

S_PolygonDataGroup f_svg_load(const std::string& path) {
	S_PolygonDataGroup 多边形数据;
	
	auto* g_image = nsvgParseFromFile(path.c_str(), "px", 96.0f);
	if (g_image) {
		NSVGshape* shape;   // 图形元素（可能包含多个路径）
		int32 shapeIndex = 0;	// 图形索引（用于区分不同图形）
		
		for (shape = g_image->shapes; shape != nullptr; shape = shape->next, ++shapeIndex) {
			多边形数据.graph.push_back(std::move(f_nsvg_Gpath(shape)));
		}
		
		多边形数据.minBound = {};
		多边形数据.bound.x = g_image->width;
		多边形数据.bound.y = g_image->height;
	}
	return 多边形数据;



	std::ifstream file(path);
	if (!file.is_open()) {
		std::cerr << "无法打开文件: " << path << std::endl;
		return {};
	}
	std::stringstream buffer;
	buffer << file.rdbuf();
	std::string svgContent = buffer.str();

	

	rapidxml::xml_document<> doc;
	doc.parse<0>(const_cast<char*>(svgContent.c_str()));
	
	rapidxml::xml_node<>* root = doc.first_node();
	rapidxml::xml_attribute<>* width = root->first_attribute("width");
	rapidxml::xml_attribute<>* heigth = root->first_attribute("heigth");

	std::istringstream iss_width{std::string(width->value())};
	std::istringstream iss_heigth{std::string(width->value())};

	iss_width >> 多边形数据.bound.x;
	iss_heigth >> 多边形数据.bound.y;

	多边形数据.maxBound = {};
	多边形数据.minBound = {};


	for (rapidxml::xml_node<>* node = root->first_node(); node; node = node->next_sibling()) {
		auto type = node->name();
		
		// 处理 fill 属性
		rapidxml::xml_attribute<>* fillAttr = node->first_attribute("fill");
		if (fillAttr) {
			std::string fillValue = fillAttr->value();
			auto isFilled = (fillValue != "none");
			auto fillColor = fillValue;
		} 
		else {
			auto isFilled = false;
			auto fillColor = "none";
		}

		mat3X2 mat = f_mat3x2_identity();
		parseNode(node, 多边形数据, mat);
	}


	return 多边形数据;
}

std::vector<PolygonData> f_svg_loads(const std::string& path) {
	std::vector<PolygonData> polygons;


	return polygons;
}



